"use strict";
exports.__esModule = true;
exports.onLoadList = void 0;
var vue_1 = require("vue");
function getLBox(lBox) {
  if (!lBox) {
    return vue_1.reactive({ loading: false, finished: false, error: false });
  }
  lBox.finished === undefined && (lBox.finished = false);
  lBox.loading === undefined && (lBox.loading = false);
  lBox.error === undefined && (lBox.error = false);
  return lBox;
}
function getForm(form) {
  if (!form) {
    return { lastId: 0, page: 1 };
  }
  else {
    if (form.lastId === undefined) {
      form.lastId = 0;
    }
    if (form.page === undefined) {
      form.page = 1;
    }
    return form;
  }
}
function getOpt(opt) {
  var result = typeof opt === "function" ? { handler: opt } : opt;
  result.lBox = getLBox(result.lBox);
  result.form = getForm(result.form);
  result.list = (result.list ? vue_1.isRef(result.list) ? result.list : vue_1.ref(result.list) : vue_1.ref([]));
  return result;
}
/**
 * 一个简单的列表请求方法
 * @param options
 */
function onLoadList(options) {
  var opt = getOpt(options);
  var onRequestSuccess = function (res) {
    if ((!res.list || !res.currentPage) && res.data) {
      res = res.data;
    }
    opt.print && console.log(typeof opt.print === "string" ? "".concat(opt.print, " ->") : 'list ->', res);
    opt.afterResponse && opt.afterResponse(res);
    opt.form.lastId = res.lastId;
    opt.form.page++;
    opt.list.value = opt.list.value.concat(res.list);
    opt.lBox.loading = false;

    if (res.currentPage >= res.lastPage) {
      opt.lBox.finished = true;
    }
  };
  var onRequestFail = function (err) {
    opt.lBox.error = true;
    throw err;
  };
  var onLoad = function () {
    opt.handler(opt.form).then(onRequestSuccess)["catch"](onRequestFail);
  };
  var onRefresh = function () {
    opt.list.value = [];
    opt.form.lastId = 0;
    opt.form.page = 1;
    opt.lBox.finished = false;
    opt.lBox.loading = true;
    if (opt.beforeRefresh) {
      opt.beforeRefresh(opt.form);
    }
    onLoad();
  };
  return {
    /**
     * 控制加载状态的盒子
     */
    lBox: opt.lBox,
    /**
     * 用来提交的表单
     */
    form: opt.form,
    /**
     * 存储数据的列表
     */
    list: opt.list,
    /**
     * 调用此方法，加载一次列表
     */
    onLoad: onLoad,
    /**
     * 调用此方法，重置页数后加载一次列表
     */
    onRefresh: onRefresh
  };
}
exports.onLoadList = onLoadList;
